package com.whilelife.Wachovia.account;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 *
 * Date: 11/9/11
 * Time: 6:05 PM
 * @author Brent Merle
 */
public class Check extends Transaction {
  private static final Pattern REGEX_LINE = Pattern.compile("(\\d*\\s*\\d{1,3}(?:[,]\\d{3})*\\.\\d{2}\\s*\\d{1,2}\\/\\d{1,2})");

  /**
   * Check numbers are just an integer
   */
  private static final Pattern REGEX_CHECK_NUMBER = Pattern.compile("^(\\d*)\\s");


  public Check(double val, String date, String descr) {
    super(val, date, descr);
  }
  
  public static List<Check> parseChecks(BufferedReader br, int endYear) throws IOException {
    ArrayList<Check> checks = new ArrayList<Check>();
    String line;
    br.readLine(); //move past the header line
    int firstMonth = -1;
    int year = endYear;
    while ((line = br.readLine()) != null) {
      line = line.trim();
      //remove any asterisks in values
      line = line.replaceAll("\\*", "");
      //A line can hold up to 3 checks
      Matcher checkMatcher = REGEX_LINE.matcher(line.replaceAll("\\*", ""));

      while (checkMatcher.find()) {
        String check = checkMatcher.group();
        Matcher numberMatcher = REGEX_CHECK_NUMBER.matcher(check);
        Matcher amountMatcher = REGEX_AMOUNT.matcher(check);
        Matcher dateMatcher = REGEX_DATE.matcher(check);
        if (!numberMatcher.find()) {
          System.err.println("Couldn't match a check number in: " + check);
          continue;
        }
        if (!amountMatcher.find()) {
          System.err.println("Couldn't match a check amount in: " + check);
          continue;
        }
        if (!dateMatcher.find()) {
          System.err.println("Couldn't match a check date in: " + check);
          continue;
        }
        String checkNumber = numberMatcher.group();
        double val = -1. * Double.parseDouble(amountMatcher.group().replaceAll(",", ""));
        String date = dateMatcher.group();
        int month = Integer.parseInt(date.substring(0, date.indexOf('/')));
        if (month < 10) {
          date = '0' + date;
        }
        if (firstMonth == -1) {
          firstMonth = month;
          if (month == 12) {
            year--;
          }
        } else if (month < firstMonth) {
          firstMonth = month;
          year++;
        }
        date += '/' + String.valueOf(year);
        checks.add(new Check(val, date, "Check " + checkNumber));
      }
      if (line.toLowerCase().contains("total")) {
        break;
      }
    }

    return checks;
  }
}
